<template>
  <div class="ble">
    <my-head title="蓝牙管理" :isRightClick = "true"/>
    <!-- <mu-text-field v-model="vin" v-show='isShowVin' placeholder="VIN" ref="vin" class='input' @keyup.enter.native=""><i class="iconfont icon-saomiao"></i></mu-text-field>
    <mu-text-field v-model="surevin" v-show='isShowSurevin' placeholder="VIN" ref="surevin" class='input' @keyup.enter.native="isPickCar()"><i class="iconfont icon-saomiao"></i></mu-text-field> -->
  
    <!-- <input type="button" name="" id="" value="打开蓝牙" @click="turnOnBluetooth" />
    <input type="button" name="" id="" value="关闭蓝牙" @click="turnOffBluetooth" />
    <input type="button" name="" id="" value="已配对的设备" @click="getPairedDevices" />
    <input type="button" name="" id="" value="搜索蓝牙设备" @click="discoveryNewDevice" /> -->
    <br>
    <mu-row gutter>
      <mu-col span="4"><div class="grid-cell"><mu-button color="primary" @click="turnOnBluetooth">打开蓝牙</mu-button></div></mu-col>
      <mu-col span="4"><div class="grid-cell"><mu-button color="primary" @click="turnOffBluetooth">关闭蓝牙</mu-button></div></mu-col>
      <mu-col span="4"><div class="grid-cell"><mu-button color="primary" @click="getPairedDevices">已配对蓝牙</mu-button></div></mu-col>
    </mu-row>
    <mu-row gutter>
      <mu-col span="4"><div class="grid-cell"><mu-button color="primary" @click="discoveryNewDevice">搜索蓝牙</mu-button></div></mu-col>
      <mu-col span="4"><div class="grid-cell"><mu-button color="primary" @click="disConnDevice">断开连接</mu-button></div></mu-col>
    </mu-row>
    <div class="my-paper">
      <h3>已配对蓝牙</h3>
      <mu-paper class="demo-paper" :z-depth="5">
        <div v-for="device in pairedDevices" class="blue-item">
          <div>名称：{{device.name}}</div>
          <div>地址：{{device.address}}</div>
          <div><mu-button color="primary" small @click="connDevice(device.address)">连接</mu-button></div>
        </div>
      </mu-paper>
    </div>
    <div class="my-paper">
      <h3>搜索的蓝牙设备</h3>
      <mu-paper class="demo-paper" :z-depth="5">
        <div v-for="device in newDevices" class="blue-item">
          <div>名称：{{device.name}}</div>
          <div>地址：{{device.address}}</div>
          <div><mu-button color="primary" small @click="connDevice(device.address)">连接</mu-button></div>
        </div>
      </mu-paper>
    </div>
    <div class="my-paper">
      <mu-text-field v-model="ml" @input="changeML" disabled></mu-text-field>
      <mu-text-field v-model="socthreshold" @input="hahaha" placeholder="SOCTHRESHOLD"></mu-text-field>
      <mu-text-field v-model="volthreshold" @input="hahaha"  placeholder="VOLTHRESHOLD"></mu-text-field>
      <mu-text-field v-model="myCommands" placeholder="请输入自定义命令" multi-line :rows="3" :rows-max="6"></mu-text-field>
      <!-- <br>xxx:{{xxx}} -->
      <br>
      <!-- <mu-button color="primary" small @click="resultVin">接收VIN</mu-button> -->
      <!-- <mu-button color="primary" small @click="resultVoltage">接收电压</mu-button> -->
      <!-- <mu-button color="primary" small @click="clearAll">清空</mu-button> -->
      <mu-button color="primary" small @click="sendCommandNmp" :disabled="sendMsgBtn">接收</mu-button>
    </div>
    <!-- <div class="my-paper">
      <textarea name="" v-model="blueResultValue" id="" cols="30" rows="10"></textarea>
      <div style="width: 100%;margin-top: 10px;min-height: 50px;word-wrap:break-word;">
        接收日志:<br>
        <textarea name="" v-model="receiveDataStrALL" id="" cols="40" rows="50"></textarea>
      </div>
    </div> -->
    <mu-dialog title="获取数据" width="360" :esc-press-close="false" :overlay-close="false" :overlay="false" :open.sync="openSimple">
      <div>vin: {{vin}}</div>
      <div>vol: {{vol}}</div>
      <div>soc: {{soc}}</div>
      <div>kol: {{kol}}</div>
      <div>mode: {{mode}}</div>
      <div>tis: {{tis}}</div>
      <div>temp: {{temp}}</div>
      <!-- <div>mileage: {{mileage}}</div>
      <div>largeBattery: {{largeBattery}}</div> -->
      <mu-button slot="actions" flat color="primary" @click="submit">提交</mu-button>
      <mu-button slot="actions" flat color="primary" @click="closeDialog">{{message}}</mu-button>
    </mu-dialog>
    <!-- <div>
      蓝牙状态：
      <div>vin: {{vin}}</div>
      <div>vol: {{vol}}</div>
      <div>soc: {{soc}}</div>
      <div>kol: {{kol}}</div>
      <div>mode: {{mode}}</div>
      <div>tis: {{tis}}</div>
      <div>temp: {{temp}}</div>
      <pre>{{bluetoothState}}</pre>
    </div> -->
    <!-- <div>
      消息：{{msg}}
    </div> -->
    <!-- <div>
      <input type="button" value="断开连接" @click="disConnDevice" />
    </div> -->
  </div>
</template>

<script>
import myHead from '@/components/header'
import api from "@/common/api"
var bluetoothTool = null;
export default {
  name: 'outlibrary',
  components: {
    myHead
  },
  data () {
    return {
      requestOnce:true,
      bluetoothState: {},
      pairedDevices: [],
      newDevices: [],
      openSimple: false,
      sendMsgBtn: false,
      receiveDataArr: [],
      sendData: "",
      isReadDone: true, // 用来检测蓝牙数据是否读取完毕
      currStatus: "", // 当前接收得是那种类型
      blueResultValue: "",
      blueResultValueVoltage: "",
      curCommand: 0, // 当前命令
      message: "读取中...",
      receiveDataStrALL: ``,
      socthreshold: "",
      volthreshold: "",
      myCommands: "",
      ml: "",
      msg: "",
      vin: "",
      vol: "",
      soc: "",
      kol: "",
      mode: "",
      tis: "",
      temp: "",
      mileage: "",
      largeBattery: "",
      xxx: "",
      rr: ``,
      command: ["ATZ","ATE0","ATSP6","ATFCSD 30 00","ATFCSH 726","ATFCSM1","ATSH 726","3E","22F190","224028","224027","22402A","22202E","224029","224025","22EFF4","22EFF5","22EF5D","ATFCSH 720","ATSH 720","ATFCSH 7D0","ATSH 7D0","ATFCSH 7E0","0902","ATFCSM1","ATSH 726","22D134","ATE1","ATRV"],
      // ATZ,ATE0,ATSP6,ATFCSD 30 00,ATFCSH 726,ATFCSM1,ATSH 726,3E,22F190,224028,224027,22402A,22202E,224029,224025,22EFF4,22EFF5,22EF5D,ATFCSH 720,ATSH 720,ATFCSH 7D0,ATSH 7D0,ATFCSH 7E0,0902,ATFCSM1,ATSH 726,22D134,ATE1,ATRV,ATSH 7E0,ATFCSH 7E0,22DD01,ATFCSM1,ATSH 7E4,ATFCSH 7E4,224845,ATFCSM1
      // command: ["ATZ", "ATE0", "ATSP6", "ATFCSD 30 00", "ATFCSH 726", "ATFCSM1", "ATSH 726", "3E", "22F190", "224028", "224027", "22402A", "22202E", "224029", "224025", "22EFF4", "22EFF5", "22EF5D", "ATFCSD 30 00", "ATFCSH 720", "ATFCSM1", "ATSH 720", "22F190", "22DD01", "224845", "ATFCSD 30 00", "ATFCSH 7D0", "ATFCSM1", "ATSH 7D0", "22F190", "ATFCSD 30 00", "ATFCSH 7E0", "ATFCSM1", "ATSH 7E0", "0902", "ATFCSD 30 00", "ATFCSH 726", "ATFCSM1", "ATSH 726", "22D134", "ATE1", "ATRV"],
      // command: ["22DD01", "224845"]
    }
  },
  methods: {
    submit(){
      this.sendMsgBtn = false;
      if(!this.vin ||
        !this.vol ||
        !this.soc ||
        !this.kol ||
        !this.mode
      ){
        alert("有值获取不完整，无法提交。");
        return false;
      }
      if(this.requestOnce){
        this.Toast.loading({message: '提交中...'});
        this.openSimple = false;
        this.requestOnce = false;
        let data = Object.assign({},this.$store.state.user,{
            content: {
              socthreshold: this.socthreshold,
              volthreshold: this.volthreshold,
              vin: this.vin,
              vol: this.vol,
              soc: this.soc,
              kol: this.kol,
              modeStr: this.mode,
              mileage: this.mileage,
              largeBattery: this.largeBattery,
              tis: this.tis,
              tempStr: this.temp,
              lat: this.$store.state.latitude,
              longStr: this.$store.state.longitude
            }
        });
        this.common.reqData(api.app('odbbluetooth'), data, res=>{
          this.requestOnce = true;
          if(res.data.status == 100){
            this.Toast({
              duration: 0,
              mask: true,
              message: "提交成功" + (this.$route.query.fromWhere == 1 ? "" : "，2秒后返回上级页面")
            });
            this.message = "读取中...",
            this.socthreshold = "";
            this.volthreshold = "";
            this.ml = "";
            this.msg = "";
            this.vin = "";
            this.vol = "";
            this.soc = "";
            this.kol = "";
            this.mode = "";
            this.tis = "";
            this.mileage = "";
            this.largeBattery = "";
            this.temp = "";
            this.xxx = "";
            this.rr = ``,
            this.curCommand = 0;
            setTimeout(() => {
              (this.$route.query.fromWhere == 2) && this.$router.go(-1);
            }, 2000);
          }else{
            this.Toast({
              duration: 0,
              mask: true,
              message: res.data.msg
            });
          }
        },err =>{
          this.requestOnce = true;
          this.Toast.clear();
        });
      }
    },
    hahaha(){
      console.log(11111);
    },
    clearAll(){
      this.currStatus = this.vin = this.blueResultValueVoltage = "";
      this.receiveDataArr = [];
    },
    turnOnBluetooth: function() {
      bluetoothTool.turnOnBluetooth();
    },
    turnOffBluetooth: function() {
      bluetoothTool.turnOffBluetooth();
    },
    getPairedDevices: function() {
      this.pairedDevices = bluetoothTool.getPairedDevices();
    },
    discoveryNewDevice: function() {
      console.log("搜索蓝牙设备");
      this.newDevices = [];
      bluetoothTool.discoveryNewDevice();
    },
    cancelDiscovery: function() {
      bluetoothTool.cancelDiscovery();
    },
    connDevice: function(address, fun) {
      window.localStorage.setItem("ble", address);
      bluetoothTool.connDevice(address, fun || (()=>{}));
    },
    disConnDevice: function() {
      bluetoothTool.disConnDevice();
    },
    closeDialog(){
      this.disConnDevice();
      this.message = "读取中...",
      this.socthreshold = "";
      this.volthreshold = "";
      this.ml = "";
      this.msg = "";
      this.vin = "";
      this.vol = "";
      this.soc = "";
      this.kol = "";
      this.mode = "";
      this.mileage = "";
      this.largeBattery = "";
      this.tis = "";
      this.temp = "";
      this.xxx = "";
      this.rr = ``,
      this.curCommand = 0;
      this.openSimple = false;
      this.sendMsgBtn = false;
    },
    sendCommandNmp(){
      if(this.myCommands){
        this.command = this.myCommands.split(",");
      }
      console.log(this.command);
      this.receiveDataStrALL = "";
      this.Toast.loading({message: '尝试连接蓝牙中，请稍后，请勿乱点'});
      this.openSimple = true;
      this.isReadDone = true;
      this.sendMsgBtn = true;
      this.message = "读取中...",
      this.socthreshold = "";
      this.volthreshold = "";
      this.ml = "";
      this.msg = "";
      this.vin = "";
      this.vol = "";
      this.soc = "";
      this.kol = "";
      this.mode = "";
      this.mileage = "";
      this.largeBattery = "";
      this.tis = "";
      this.temp = "";
      this.xxx = "";
      this.rr = ``,
      this.curCommand = 0;
      this.connDevice(window.localStorage.getItem("ble"), ()=>{
        this.Toast.clear();
        this.sendCommand();
      });
    },
    sendCommand(){
      this.ml = this.sendData = this.command[this.curCommand]+"\r";
      this.command[this.curCommand] && this.isReadDone && this.onSendData();
      !this.command[this.curCommand] && (this.message = "读取完毕，点击关闭") && (this.curCommand = 0) && (this.sendMsgBtn = false) && (this.disConnDevice());
    },
    resultVoltage(){
      this.currStatus = "voltage";
      this.ml = this.sendData = "AT RV\r";
      this.isReadDone && this.onSendData();
    },
    resultVin(){
      this.currStatus = "vin";
      this.ml = this.sendData = "09 02\r";
      this.isReadDone && this.onSendData();
    },
    onSendData: function() {
      this.isReadDone = false;
      bluetoothTool.sendData(this.sendData);
    },
    hexCharCodeToStr(hexCharCodeStr) {
    　　var trimedStr = hexCharCodeStr.trim();
    　　var rawStr = 
    　　trimedStr.substr(0,2).toLowerCase() === "0x"
    　　? 
    　　trimedStr.substr(2) 
    　　: 
    　　trimedStr;
    　　var len = rawStr.length;
    　　if(len % 2 !== 0) {
        console.log("Illegal Format ASCII Code!编码解码失败");
        return "";
    　　}
    　　var curCharCode;
    　　var resultStr = [];
    　　for(var i = 0; i < len;i = i + 2) {
    　　　　curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
    　　　　resultStr.push(String.fromCharCode(curCharCode));
    　　}
    　　return resultStr.join("");
    },
    changeML(v){
      this.ml = v;
      this.sendData = v + "\r";
      console.log(this.sendData)
    },
    onAt(){
      this.sendData = ">ATRV\r";
    },
    onST(){
      this.sendData = ">STVR\r";
    },
    strToHexCharCode(){
    },
  },
  created(){
    let that = this;
    console.log("that.common",that.common)
    bluetoothTool = that.common.BluetoothTool();
    this.bluetoothState = bluetoothTool.state;
    bluetoothTool.init({
      listenBTStatusCallback: function(state) {
        that.msg = "蓝牙状态: " + state;
      },
      discoveryDeviceCallback: function(newDevice) {
        that.newDevices.push(newDevice);
      },
      discoveryFinishedCallback: function() {
        that.msg = "搜索完成";
      },
      readDataCallback: function(dataByteArr) {
        that.receiveDataArr.push.apply(that.receiveDataArr, dataByteArr);
      },
      connExceptionCallback: function(e) {
        console.log(e);
        that.connDevice(window.localStorage.getItem("ble"));
        that.msg = "设备连接失败";
      }
    });
  },
  mounted () {
    this.$nextTick(()=>{
      // this.$router.go(-1);
      // this.connDevice(window.localStorage.getItem("ble"));
    });
  },
  computed: {
    receiveDataStr: function() {
      return String.fromCharCode.apply(String, this.receiveDataArr);
    },
    bluetoothStatusDesc: function() {
      return this.bluetoothStatus ? "已开启" : "已关闭";
    },
    latitudeChange () {
      return this.$store.state.latitude;
    },
    longitudeChange () {
      return this.$store.state.longitude;
    },
    speedChange () {
      return this.$store.state.speed;
    }
  },
  watch:{
    receiveDataStr: function(){
      // 判断是否结束
      if(/(NO DATA|\>|STOPPED|OK)$/.test(this.receiveDataStr)){
        this.msg += this.command[this.curCommand] + "_:_" + this.receiveDataStr;
        // this.blueResultValue +=this.receiveDataStr.replace("AT RV", "").replace(">", "").replace("0:", ":").replace("1:", ":").replace("2:", ":").replace("3:", ":").replace("4:", ":")+'\r';
        // this.blueResultValue += this.receiveDataStr + "";
        this.blueResultValue = this.receiveDataStr;
        this.receiveDataStrALL += this.command[this.curCommand] + ":\n" + this.receiveDataStr + "\n";
        if(this.blueResultValue.indexOf("62 F1 90") >= 0 || this.blueResultValue.indexOf("49 02") >= 0){
          if(this.vin == ""){
            let str = "";
            if(this.blueResultValue.indexOf("62 F1 90") >= 0){
              str = this.blueResultValue.replace(">", "")
              .replace("01B 0: 62 F1 90 ", "")
              .replace("01B 0:62 F1 90 ", "")
              .replace(" 3: 00 00 00 00 00 00 00", "")
              .replace(" 3:00 00 00 00 00 00 00","")
              .replace("3: 00 00 00 00 00 00 00", "")
              .replace("3:00 00 00 00 00 00 00","")
              .replace("1: ","")
              .replace("1:","")
              .replace("2: ","")
              .replace("2:","");
              console.log("blueResultValue A:"+str);
            }else if(this.blueResultValue.indexOf("49 02")>=0){
              str = this.blueResultValue.replace(">", "")
              .replace("014 0: 49 02 01 ", "")
              .replace("014 0:49 02 01 ", "")
              .replace("1: ","")
              .replace("1:","")
              .replace("2: ","")
              .replace("2:","");
              // console.log("blueResultValue B:" + str);
            }
            this.vin = "";
            let arr = str.split(" ");
            console.log("vin_arr:"+JSON.stringify(arr));
            for(let i=1;i<arr.length;i++){
              this.vin += this.hexCharCodeToStr(arr[i]);
              console.log("转换中："+ arr[i] + " _ " + this.hexCharCodeToStr(arr[i]))
            }
          }
        }else if(this.blueResultValue.indexOf("40 28") >= 0){
          // SOC电瓶
          let strSoc = this.blueResultValue.replace(">", "")
          .replace(" > ", "")
          .replace(" >", "")
          .replace("> ", "")
          .replace("62 40 28 ", "")
          .replace("62 40 28", "");
          this.soc = parseInt(strSoc, 16) + "%";
        }else if(this.blueResultValue.indexOf("40 27") >= 0){
          // tis
          let strTis = this.blueResultValue.replace(">", "")
          .replace(" > ", "")
          .replace(" >", "")
          .replace("> ", "")
          .replace("62 40 27 ", "")
          .replace("62 40 27", "");
          this.tis = parseInt(strTis, 16) + "days";
        }else if(this.blueResultValue.indexOf("40 29") >= 0){
          // Temp
          let strTemp = this.blueResultValue.replace(">", "")
          .replace(" > ", "")
          .replace(" >", "")
          .replace("> ", "")
          .replace("62 40 29 ", "")
          .replace("62 40 29", "");
          this.temp = parseInt(strTemp, 16) + "°C";
        }else if(this.blueResultValue.indexOf("40 25") >= 0){
          // KOL
          let strKol = this.blueResultValue.replace(">", "")
          .replace(" > ", "")
          .replace(" >", "")
          .replace("> ", "")
          .replace("62 40 25 ", "")
          .replace("62 40 25", "");
          let arr = strKol.split(" ");
          // for(let i=1;i<arr.length;i++){
          //   this.kol += hex2int(arr[i]);
          // }
          this.kol = parseInt(arr[0], 16) + "mA";
        }else if(this.blueResultValue.indexOf("D1 34") >= 0){
          let strMode = this.blueResultValue.replace(">", "")
          .replace(" > ", "")
          .replace(" >", "")
          .replace("> ", "")
          .replace(" OK>", "")
          .replace(" OK", "")
          .replace("OK", "")
          .replace("62 D1 34 ", "")
          .replace("62 D1 34", "");
          console.log("mode:"+strMode+"mode10:"+parseInt(strMode, 16));
          this.mode = parseInt(strMode, 16);
          if(this.mode == 0){
            this.mode = "NORMAL";
          }else if(this.mode == 1){
            this.mode = "FACTORY";
          }else if(this.mode == 3){
            this.mode = "TRANSPORT";
          }
        }
        // else if(this.blueResultValue.indexOf("DD 01") >= 0 || this.blueResultValue.indexOf("DD01") >= 0){
        //   let strLc = this.blueResultValue.replace(">", "").replace(/\n/g,"").replaceAll(" ", "")
        //   .replace("22DD01", "")
        //   .replace("OK", "")
        //   .replace("STOPPED", "")
        //   .replace("62DD01", "");
        //   // this.mileage = parseInt(strLc, 16);
        //   this.mileage = strLc;
        // }
        // else if(this.blueResultValue.indexOf("48 45") >= 0 || this.blueResultValue.indexOf("4845") >= 0){
        //   let strLkoc = this.blueResultValue.replace(">", "").replace(/\n/g,"").replaceAll(" ", "")
        //   .replace("224845", "")
        //   .replace("OK", "")
        //   .replace("STOPPED", "")
        //   .replace("62 48 45", "");
        //   // this.largeBattery = parseInt(strLkoc, 16) / 2;
        //   this.largeBattery = strLkoc;
        // }
        else if(this.blueResultValue.indexOf("ATRV") >= 0){
          let strVol = this.blueResultValue
          .replace("ATRV ", "")
          .replace("ATRV", "")
          .replace(">", "");
          this.vol = strVol;
        }
        this.currStatus = "";
        this.isReadDone = true;
        this.receiveDataStr = "";
        this.receiveDataArr = [];
        this.curCommand ++;
        this.sendCommand();
      }
    },
    latitudeChange: function(data) {
    },
    longitudeChange: function(data) {
    },
    speedChange: function(data) {
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.outlibrary{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.btn{
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
}
.btn .mu-raised-button{
  font-size: 18px;
  height: 40px;
  line-height: 40px;
}
.input{
    display: block;
    margin: 15px auto;
    width: 85%;
}
.paper, .state, .msg{
    width: 85%;
    margin: 1em auto 0;
    padding: 1.5em 0;
}
.list-content{
    padding: 5px 20px;
}
.library-position{
    font-size: 1.5em;
    font-weight: bold;
    color: red;
    text-shadow: 2px 2px 5px rgba(0,0,0,0.5);
}
em{
  padding: 0 10px;
}
.mark6{
  font-style: normal;
  color: red;
  font-size: 1.25em;
}
.demo-container {
}
.row {
  margin-bottom: 10px;
}
.grid-cell {
  border-radius: 4px;
  height: 36px;
  text-align: center;
  background: rgba(255, 255, 255, 0.8);
}
.demo-container.is-stripe .col:nth-child(2n) .grid-cell{
  background: rgba(0, 0, 0, 0.54);
}
.my-paper{
  width: 95%;
  margin: 0 auto 20px;
}
.my-paper h3{
  font-size: 1rem;
  font-weight: normal;
  margin-bottom: 5px;
}
.my-paper .mu-paper{
  max-height: 8rem;
  overflow-x: hidden;
  overflow-y: auto;
  border-radius: 0;
  padding: 10px;
}
.blue-item{
  margin: 0 0 10px;
}
</style>
